<template>
    <van-cascader
  v-if="dataType==='static'"
    v-model="cascaderValue"
    title="请选择级联选择"
    :options="optionsCopy"
    :field-names="fieldNames"
    @finish="onFinish"
  />
  <van-cascader
  v-else
    v-model="cascaderValue"
    title="请选择级联选择"
    :options="dynamicOption"
    :field-names="fieldNames"
    @change="dynamicDataChange"
    @finish="onFinish"
  />
</template>
<script>
import {
  getColumnData,
  getDictData,
  getCascadeData
} from '@/api/custom/formDesigner'
export default {
  data() {
    return {
      cascaderValue: "",
      dataType:'',
      options:[],
      fields:[],
      formName:'',
      fieldNames:{
        text: 'label',
        value: 'value',
        children: 'children',
      },
      optionsCopy: [],
      dynamicOption:[],
      value:''
    };
  },
  props: {
    cascaderobj: {
      type: Object,
      default: function () {
        return {};
      },
    },
    showh5cascader:{
      type:Boolean,
      default:false
    }
  },
  watch:{
    showh5cascader:{
      handler(){
        this.dataType = this.cascaderobj.dataType;
    this.options = this.cascaderobj.options;
    this.fields = this.cascaderobj.fields;
    this.formName = this.cascaderobj.formName;
    this.value = this.cascaderobj.__config__.defaultValue;
    this.cascaderValue = '';
    this.optionsCopy = [];
    this.dynamicOption = [];
    this.getH5cascaderData();
      },
      immediate:true
    }
  },
  methods: {
    dynamicDataChange(val){
      let ind = val.tabIndex + 1;
      let _this = this;
      if(ind !== this.fields.length){
        getCascadeData({
          tableName: _this.fields[ind].tableName,
          tableColumn: _this.fields[ind].datas[0].fieldName,
          linkColumn: _this.fields[ind].datas[0].parent,
          showName: _this.fields[ind].datas[0].showName,
          parentTableName: ind > 0 ? _this.fields[ind - 1].tableName : '',
          parentTableColumn: ind > 0 ? _this.fields[ind - 1]?.datas[0].fieldName : '',
          parentShowColumn: ind > 0 ? _this.fields[ind - 1]?.datas[0].showName : '',
          value: val.value
        }).then(rsp => {
            if (rsp.code === 0) {
                const nodes = rsp.data || []
                if(ind<_this.fields.length-1){
                  nodes.forEach(t=>{t.children = []});
                }
                let obj;
                function handlerDynamic(arr){
                  arr.forEach(cent=>{
                    if(Array.isArray(cent.children) && cent.children.length){
                      handlerDynamic(cent.children);
                    }else if(cent.value===val.value){
                      obj = cent;
                      return;
                    }
                  });
                };
                handlerDynamic(_this.dynamicOption);
                if(typeof obj === 'object'){
                  obj.children.push(...nodes);
                }
            }
        })
      }
    },
    getH5cascaderData(){
      if(this.dataType==='static'){
        if (this.value?.length > 0) {
            let keys = [...this.value]
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(this.options, keys, index, str)
            this.makeOptions(str)
            this.optionsCopy = [...this.options]
        } else {
            this.optionsCopy = [...this.options]
        }
        this.handlerStatic(this.optionsCopy);
      }else{
        this.getdynamicData();
      }
    },
    handlerStatic(arr){
      arr.forEach(item=>{
        if(Array.isArray(item.children)){
          if(item.children.length){
            this.handlerStatic(item.children);
          }else{
            delete item.children;
          }
        }
      });
    },
     getdynamicData(val) {
      // 新需求适配多个表单
       getCascadeData({
          tableName: this.fields[0].tableName,
          tableColumn: this.fields[0].datas[0].fieldName,
          linkColumn: this.fields[0].datas[0].parent,
          showName: this.fields[0].datas[0].showName,
          value: val
      }).then(rsp => {
          if (rsp.code === 0) {
              this.dynamicOption = rsp.data || []
              this.dynamicOption.forEach(val=>{
                val.children = [];
              });
          }
      })
    },
    getLabelByKey(options, key, index, str) {
        options?.length > 0 && options.forEach((item) => {
          if (item.value.toString() === key[index] + '' || item.label === key[index] + '') {
            str.push({label: item.label, value: key[index]})
            index++
            index < key.length && this.getLabelByKey(item.children, key, index, str)
            return true
          }
        })
    },
    makeOptions (list) {
        let copyOption = []
        list.forEach((item, index) => {
            if (index === 0) {
                copyOption.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 1) {
            copyOption[0].children = [];
                copyOption[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 2) {
            copyOption[0].children[0].children = [];
                copyOption[0].children[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 3) {
            copyOption[0].children[0].children[0].children = [];
                copyOption[0].children[0].children[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
        })
        this.optionsCopy = [...copyOption]
    },
    onFinish({ selectedOptions }) {
      this.$emit(
        "cascaderChange",
        selectedOptions,
        this.cascaderobj.modelValueCur
      );
    }
  },
};
</script>
